<template>
  <div class="product-list">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input v-model.number="searchForm.minPrice" placeholder="最低价" style="width: 100px" />
          <span style="margin: 0 10px">-</span>
          <el-input v-model.number="searchForm.maxPrice" placeholder="最高价" style="width: 100px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </div>
      </template>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="imageUrl" label="商品图片">
          <template #default="scope">
            <el-image 
              :src="scope.row.imageUrl" 
              style="width: 50px; height: 50px" 
              fit="cover"
              v-if="scope.row.imageUrl"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量" width="80" />
        <el-table-column prop="inventory" label="库存" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAd" label="广告" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isAd === 1 ? 'warning' : 'info'">
              {{ scope.row.isAd === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleChangeStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑商品弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑商品" width="600px" @close="handleDialogClose">
      <el-form 
        :model="editProductForm" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editProductForm.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品图片" prop="imageUrl">
          <el-input v-model="editProductForm.imageUrl" placeholder="请输入图片链接" />
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="editProductForm.price" 
            :min="0" 
            :precision="2" 
            :step="0.1" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="库存" prop="inventory">
          <el-input-number 
            v-model="editProductForm.inventory" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="销量" prop="sales">
          <el-input-number 
            v-model="editProductForm.sales" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="评论数" prop="comments">
          <el-input-number 
            v-model="editProductForm.comments" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="是否广告" prop="isAd">
          <el-switch 
            v-model="editIsAdSwitch" 
            active-text="是" 
            inactive-text="否"
            @change="handleEditAdChange"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch 
            v-model="editStatusSwitch" 
            active-text="上架" 
            inactive-text="下架"
            @change="handleEditStatusChange"
          />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-input v-model="editProductForm.tags" placeholder="请输入商品标签，多个标签用逗号分隔。例如：[&quot;小米&quot;, &quot;手机&quot;]" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="editLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import productApi, { type ProductType } from '@/api/product'

// 搜索表单
const searchForm = ref({
  name: '',
  minPrice: undefined,
  maxPrice: undefined
})

// 分页参数
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<ProductType[]>([])
const loading = ref(false)

// 路由
const router = useRouter()

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const editLoading = ref(false)

// 编辑表单数据
const editProductForm = ref<ProductType>({
  id: 0,
  name: '',
  imageUrl: '',
  price: 0,
  sales: 0,
  comments: 0,
  isAd: false,
  inventory: 0,
  status: 1,
  tags: ''
})

// 编辑广告开关和状态开关（用于UI展示）
const editIsAdSwitch = ref(false)
const editStatusSwitch = ref(true)

// 编辑表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  inventory: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请输入商品标签', trigger: 'blur' }
  ]
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    const res: any = await productApi.getProductList(
      pagination.value.pageNo,
      pagination.value.pageSize,
      'id',
      false
    )
    tableData.value = res.data.data.list
    pagination.value.total = res.data.data.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索商品
const searchProduct = async () => {
  loading.value = true
  try {
    const res: any = await productApi.searchProduct(
      pagination.value.pageNo,
      pagination.value.pageSize,
      'id',
      false,
      searchForm.value.name,
      searchForm.value.minPrice || 0,
      searchForm.value.maxPrice || 0
    )
    tableData.value = res.data.data.list
    pagination.value.total = res.data.data.total
  } catch (error) {
    ElMessage.error('搜索商品失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNo = 1
  if (searchForm.value.name || searchForm.value.minPrice !== undefined || searchForm.value.maxPrice !== undefined) {
    searchProduct()
  } else {
    getProductList()
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    minPrice: undefined,
    maxPrice: undefined
  }
  pagination.value.pageNo = 1
  getProductList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.pageNo = val
  handleSearch()
}

// 新增商品
const handleAdd = () => {
  router.push('/product/add')
}

// 编辑商品
const handleEdit = async (row: ProductType) => {
  try {
    // 获取商品详情
    const res: any = await productApi.getProductDetail(row.id)
    const detail = res.data.data
    
    // 填充表单数据
    editProductForm.value = {
      id: detail.id,
      name: detail.name,
      imageUrl: detail.imageUrl,
      price: detail.price,
      sales: detail.sales,
      comments: detail.comments,
      isAd: detail.isAd,
      inventory: detail.inventory,
      status: detail.status,
      tags: detail.tags
    }
    
    // 设置开关状态
    editIsAdSwitch.value = detail.isAd === 1
    editStatusSwitch.value = detail.status === 1
    
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取商品详情失败')
  }
}

// 处理广告开关变化
const handleEditAdChange = (val: boolean) => {
  editProductForm.value.isAd = val
}

// 处理状态开关变化
const handleEditStatusChange = (val: boolean) => {
  editProductForm.value.status = val ? 1 : 0
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      editLoading.value = true
      try {
        const res: any = await productApi.updateProduct(editProductForm.value)
        
        if (res.data.code === 200) {
          ElMessage.success('更新商品成功')
          editDialogVisible.value = false
          getProductList()
        } else {
          ElMessage.error(`更新商品失败: ${res.data.msg}`)
        }
      } catch (error) {
        ElMessage.error('更新商品失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

// 关闭弹窗时的处理
const handleDialogClose = () => {
  editFormRef.value.resetFields()
}

// 更改商品状态
const handleChangeStatus = (row: ProductType) => {
  ElMessageBox.confirm(
    `确定要${row.status === 1 ? '下架' : '上架'}该商品吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里应该调用API更改商品状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success('操作成功')
  }).catch(() => {
    // 取消操作
  })
}

// 初始化加载数据
onMounted(() => {
  getProductList()
})
</script>

<style scoped>
.product-list {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>